package com.kaifamiao.mapper;

import com.kaifamiao.entity.Customer;
import com.kaifamiao.type.BooleanTypeHandler;
import com.kaifamiao.type.LocalDateTypeHandler;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CustomerMapper {

    @Select( "SELECT id, email, tel, password, birthdate, married FROM t_customers WHERE id = #{id}")
    @Results( id="customerResultMap", value = {
                @Result( id = true , column = "id", property = "id"),
                @Result( column = "email", property = "email"),
                @Result( column = "tel", property = "tel"),
                @Result( column = "password", property = "password"),
                @Result( column = "birthdate", typeHandler = LocalDateTypeHandler.class, property = "birthdate"),
                @Result( column = "married", typeHandler = BooleanTypeHandler.class, property = "married"),
              })
    Customer find( Integer id );

    @Select( "SELECT id, email, tel, password, birthdate, married FROM t_customers ORDER BY id")
    @ResultMap("customerResultMap")
    List<Customer> findAll();

    @Select( "SELECT id, email, tel, password, birthdate, married FROM t_customers WHERE email = #{email} OR tel = #{tel}")
    @ResultMap("customerResultMap")
    Customer findByEmailOrTel( @Param("email") String email, @Param("tel") String tel );

    @Insert("INSERT INTO t_customers " +
            "(id, email, tel, password, birthdate, married) " +
            "VALUES " +
            "( #{id}, #{email}, #{tel}, #{password}, #{birthdate, typeHandler=LocalDateTypeHandler}, #{married, typeHandler=BooleanTypeHandler})")
    @SelectKey( statement = "SELECT IFNULL( MAX(id), 0 ) + 1 FROM t_customers",
                resultType = int.class,
                keyProperty = "id",
                databaseId = "mysql",
                before = true)
    @SelectKey( statement = "SELECT NVL( MAX(id), 0 ) + 1 FROM t_customers",
                resultType = int.class,
                keyProperty = "id",
                databaseId = "oracle",
                before = true)
    int persist( Customer c );

    @Update("UPDATE t_customers " +
            "SET " +
            "email = #{email}, " +
            "tel = #{tel}, " +
            "birthdate = #{birthdate, typeHandler=LocalDateTypeHandler}," +
            "married = #{married, typeHandler=BooleanTypeHandler} " +
            "WHERE id = #{id}")
    int update( Customer c );

    @Delete( "DELETE FROM t_customers WHERE id = #{id}" )
    int remove( Integer id );

}
